<template>
  <div id="positiveSampleQuery">
    <Breadcrumb content="阳性标本查询" />
    <div class="bodyContent">
      <vxe-toolbar perfect>
        <template #buttons>
          <el-form :model="searchForm" class="form-input-m" label-width="80px" :inline="true">
            <el-form-item label="报告单元">
              <SelectWorkGroupAllDefaultAll ref="selectWorkGroupRef" :url="'/api/rptGroup/findRptGroup'"
                :inputWidth="'100%'" @fatherMethod="searchWklt" :isShowAll="true" :isClear="true">
              </SelectWorkGroupAllDefaultAll>
            </el-form-item>
            <el-form-item label="科室">
              <vxe-input v-enterNextInput class="enterNextInputFlag" type="text" v-model="searchForm.reqDept" clearable
                class-name="width-100-percentage"></vxe-input>
            </el-form-item>
            <el-form-item label="统计日期">
              <el-date-picker v-model="searchForm.countTime" value-format="YYYY-MM-DD" type="daterange"
                range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="样本类型">
              <SelectDataList ref="sampleTypeRef" :url="'/api/lab/labSampleType/findSampleTypeList'" :displayField="[
                { title: '编码', props: 'sampleTypeCode' }, //列标题
                { title: '类型名称', props: 'sampleTypeName' }
              ]" :placeholder="'点击选择样本类型'" @selectDataRow="SelectRowClick1" v-model="searchForm.sampleTypeNa" />
            </el-form-item>

            <el-row>
              <el-form-item label="细菌组" prop="germType">
                <SelectDataList ref="employeeSelectRef" :url="'/api/sys/basDictDetail/findDictDetailList'" :displayField="[
                  { title: '编码', props: 'code' }, //列标题
                  { title: '名称', props: 'name' }
                ]" :placeholder="'点击选择细菌组'" :searchParam="{ code: 'germType' }" @clearValue="clearValueHandler"
                  @selectDataRow="SelectRowClick" v-model="searchForm.germTypeNa" />
              </el-form-item>
              <el-form-item label="细菌">
                <SelectDataList ref="employeeSelectRef" :url="'/bac/germ/dict/getGermsByParams'" :displayField="[
                  { title: '编码', props: 'germNo' }, //列标题
                  { title: '名称', props: 'germNa' }
                ]" :placeholder="'点击选择细菌'" :searchParam="{ code: 'bacteria' }" @clearValue="clearValueHandler3"
                  @selectDataRow="SelectRowClick3" v-model="searchForm.bacteria" />
              </el-form-item>
              <el-form-item label="去除重复" prop="color">
                <template #default>
                  <el-checkbox v-model="searchForm.isDistinct" :true-label="1" :false-label="0" @click="getLyReagent"></el-checkbox>
                </template>
              </el-form-item>
            </el-row>
            <el-form-item>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="查询"
                @click="getLyReagent"></vxe-button>
              <!-- <vxe-button type="text" class="button-blue" icon="vxe-icon-print" content="打印"
                @click="getLyReagent"></vxe-button> -->
              <vxe-button type="text" class="button-blue" icon="vxe-icon-download" content="导出阳性标本统计"
                @click="exportExcel('#printTest', '阳性标本统计', 1)"></vxe-button>&nbsp;&nbsp;
            </el-form-item>
          </el-form>
        </template>
      </vxe-toolbar>
      <div class="leftTable">
        <vxe-table :loading="feeItemShowLoading" ref="feeitemVsItemdictTable" border class="mytable-scrollbar"
          height="auto" show-header-overflow show-overflow align="left" :row-config="{ isCurrent: true, isHover: true }"
          @current-change="instrRowClick" :data="bacTestCountList" :edit-config="{ trigger: 'click', mode: 'cell' }"
          :column-config="{ resizable: true }">
          <!-- <vxe-column type="checkbox" width="30px" align="center"></vxe-column> -->
          <vxe-column type="seq" title="序号" width="30"></vxe-column>
          <vxe-column field="rptGroup" title="报告单元"></vxe-column>
          <vxe-column field="sampleda" title="日期" width="100"></vxe-column>
          <vxe-column field="sampleNo" title="标本号"></vxe-column>
          <vxe-column field="patTypeNa" title="病人类型" width="60"></vxe-column>
          <vxe-column field="reqDeptNa" title="申请科室"></vxe-column>
          <vxe-column field="patNo" title="病历号"></vxe-column>
          <vxe-column field="patNa" title="姓名"></vxe-column>
          <vxe-column field="sex" title="性别" width="35" show-overflow>
            <template #default="{ row }">{{ row.sex === '1' ? '男' : row.sex === '2' ? '女' : '未知' }}</template>
          </vxe-column>
          <vxe-column field="age" title="年龄" width="60">
            <template #default="{ row }">{{ row.age + row.ageUnit }}</template>
          </vxe-column>
          <vxe-column field="reqPurpose" title="检验目的"></vxe-column>
          <vxe-column field="germNa" title="细菌"></vxe-column>
          <vxe-column field="reqNo" title="条码号"></vxe-column>
          <vxe-column field="sampleTypeNa" title="标本类型"></vxe-column>
          <vxe-column field="reqDoctorNa" title="申请医生"></vxe-column>
          <vxe-column field="reqTime" title="申请时间"></vxe-column>
          <vxe-column field="diagnose" title="诊断"></vxe-column>
        </vxe-table>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
// 引入组件区 ==========
import Breadcrumb from '@/components/Breadcrumb.vue';
import { ref, reactive, getCurrentInstance, onMounted, watch } from 'vue';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示信息
import { AppStore } from '@/stores/store';
import { isEmpty } from 'lodash';
import SelectWorkGroupAllDefaultAll from '../lab_bus/components/SelectWorkGroupAllDefaultAll.vue'; //报告单元默认全部引入下拉组件
import SelectDataList from '@/components/SelectDataList.vue';

let store = AppStore();
// 全局变量定义区 ==========
// 变量定义区
let { proxy }: any = getCurrentInstance();
const itemDictList = reactive([]);
//样本类型
let selevctFeeItemRow: any = reactive({
  id: ''
});

let showLoading = ref(false); //刷新+表格加载
let feeItemShowLoading = ref(false);
let searchValue = ref('');
const searchForm = reactive({
  rptGroup: '',
  reqDept: '',
  countTime: getDefaultDateRange(),
  sampleType: '',
  sampleTypeNa: '',
  reagentSearchValue: '',
  bacteria: '',
  isDistinct: 0,
  germType: '',
  germTypeNa: '',
  resiPhenCodes: [],
  resiPhens: [],
  orgId: store.userInfo.orgId,
  name: store.userInfo.orgName
});

let germNo = ref(null);
let resiPhenNa = ref(null);
let germNa = ref(null);
const bacTestCountList = reactive([]);
// 方法定义区 =============
onMounted(() => {
  getLyReagent();
});


function getDefaultDateRange() {
  const end = new Date(); // 当前时间
  const start = new Date();
  start.setTime(start.getTime() - 3 * 24 * 3600 * 1000); // 3天前

  // 格式化为 'yyyy-MM-dd'
  const formatDate = (date) => {
    const yyyy = date.getFullYear();
    const mm = String(date.getMonth() + 1).padStart(2, '0');
    const dd = String(date.getDate()).padStart(2, '0');
    return `${yyyy}-${mm}-${dd}`;
  };

  return [formatDate(start), formatDate(end)];
}

// function mergeRowMethod({ row, _rowIndex, column, visibleData }) {
//   const fields = ['germNo', 'germNa', 'detGerm', 'detRateGerm', 'detRes', 'detRateRes']
//   const cellValue = row[column.field]
//   if (cellValue && fields.includes(column.field)) {
//     const prevRow = visibleData[_rowIndex - 1]
//     let nextRow = visibleData[_rowIndex + 1]
//     if (prevRow && prevRow[column.field] === cellValue && prevRow.germNo === row.germNo) {
//       return { rowspan: 0, colspan: 0 }
//     } else {
//       let countRowspan = 1
//       while (nextRow && nextRow[column.field] === cellValue && nextRow.germNo === row.germNo) {
//         nextRow = visibleData[++countRowspan + _rowIndex]
//       }
//       if (countRowspan > 1) {
//         return { rowspan: countRowspan, colspan: 1 }
//       }
//     }
//   }
// }

function SelectRowClick(row) {
  searchForm.germType = row.code;
  searchForm.germTypeNa = row.name;
}
function SelectRowClick1(row) {
  searchForm.sampleType = row.sampleTypeCode;
  searchForm.sampleTypeNa = row.sampleTypeName;
}
function SelectRowClick3(row) {
  searchForm.bacteria = row.germNo;
  getLyReagent();
}

//获取工作列表
function searchWklt(selectedRadioId, selectedName) {
  searchForm.rptGroup = selectedRadioId.value;
}

function instrRowClick({ row }: any) {
  (proxy.$refs.feeitemVsItemdictTable as any).setCurrentRow(row);
  germNo.value = row.germNo;
  resiPhenNa.value = row.resiPhenNa;
  germNa.value = row.germNa;
  getOpenEmptyBoxList();
}

function getOpenEmptyBoxList() {
  findOpenEmptyBoxList(selevctFeeItemRow);
}

// 获取报告项目列表
function findOpenEmptyBoxList(row: any) {
  itemDictList.length = 0;
  showLoading.value = true;
  const url = '/bac_count/findBacDrugCount';
  let obj = {
    params: {
      rptGroup: searchForm.rptGroup,
      reqDept: searchForm.reqDept,
      startTime: (searchForm.countTime ? searchForm.countTime[0] : null),
      endTime: (searchForm.countTime ? searchForm.countTime[1] : null),
      sampleType: searchForm.sampleType,
      germType: searchForm.germType,
      bacteria: searchForm.bacteria,
      isDistinct: searchForm.isDistinct,
      germNo: germNo.value,
      resiPhenNa: resiPhenNa.value
    }
  };
  proxy.$http
    .get(url, obj)
    .then((res: any) => {
      if (res.data && res.data.length > 0) {
        itemDictList.push(...res.data);
      }
      showLoading.value = false;
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
      showLoading.value = false;
    });
}

// 获取中间的报告单元信息
function getLyReagent() {
  bacTestCountList.length = 0;
  feeItemShowLoading.value = true;
  const url = '/bac_count/findPositiveSample';
  let obj = {
    params: {
      rptGroup: searchForm.rptGroup,
      reqDept: searchForm.reqDept,
      startTime: (searchForm.countTime ? searchForm.countTime[0] : null),
      endTime: (searchForm.countTime ? searchForm.countTime[1] : null),
      sampleType: searchForm.sampleType,
      germType: searchForm.germType,
      bacteria: searchForm.bacteria,
      isDistinct: searchForm.isDistinct,
      resiPhenCodes: searchForm.resiPhenCodes.join(','),
      orgId: searchForm.orgId
    }
  };
  proxy.$http
    .get(url, obj)
    .then((res: any) => {
      if (res && res.data && res.data.length > 0) {
        bacTestCountList.push(...res.data);
        console.log('bacTestCountList', bacTestCountList);

        // if (bacTestCountList.length > 0) {
        //   const kn = bacTestCountList.find((k) => k.id == selevctFeeItemRow.id);
        //   if (isEmpty(kn)) {
        //     instrRowClick({ row: bacTestCountList[0] });
        //   } else {
        //     instrRowClick({ row: kn });
        //   }
        // } else {
        //   selevctFeeItemRow.id = '';
        // }
      } else {
        itemDictList.length = 0;
        selevctFeeItemRow.id = '';
      }
      feeItemShowLoading.value = false;
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
      feeItemShowLoading.value = false;
    });
}

//导出excel
function exportExcel(dom, title, type) {
  if (type == 1) {
    const $table = proxy.$refs.feeitemVsItemdictTable as any;
    $table.exportData({ data: bacTestCountList, type: 'csv', filename: title, useStyle: true });
  } else {
    const $table = proxy.$refs.itemDictTable as any;
    $table.exportData({ data: itemDictList, type: 'csv', filename: title, useStyle: true });
  }
}
// 清空组件输入框
function clearValueHandler() {
  searchForm.germType = '';
  searchForm.germTypeNa = '';
}
// 清空组件输入框
function clearValueHandler3() {
  searchForm.bacteria = '';
  getLyReagent();
}
</script>
<style lang="scss" scoped>
#positiveSampleQuery {
  height: 100%;

  .bodyContent {
    height: calc(100% - 60px);

    .area {
      background-color: $base-white;
    }

    // 附加按钮间距
    .button-blue,
    .button-red {
      margin: 5px 0 5px 5px;
    }

    // 查询按钮
    .SearchBtn {
      margin-right: 5px;
    }
  }

  .splitpanes {
    background-color: $base-white;
    height: calc(100% - 122px);
  }

  :deep(.splitpanes__pane) {
    overflow: visible;
  }

  .dialogFooter {
    text-align: right;
  }

  .rightTable {
    height: calc(100% - 50px);
  }

  .leftTable {
    height: calc(100% - 0px);
  }
}
</style>
